﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 服务器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void jtbtn_Click(object sender, EventArgs e)
        {
            Socket st = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Thread rd = new Thread(JtSocket);
            rd.IsBackground = true;
            Control.CheckForIllegalCrossThreadCalls = false;
            rd.Start(st);

        }
        private void JtSocket(object ob)
        {
            Socket sk = ob as Socket;
            IPAddress ip = IPAddress.Parse(IPBox1.Text);
            IPEndPoint dk = new IPEndPoint(ip, Convert.ToInt32(duankoutxt01.Text));
            sk.Bind(dk);
            sk.Listen(2);
            Thread ed = new Thread(JieShou);
            ed.IsBackground = true;
            Control.CheckForIllegalCrossThreadCalls = false;
            ed.Start(sk);

        }
        private void JieShou(object ob)
        {

            Socket sk = ob as Socket;
            while (true)
            {
                Socket so = sk.Accept();
                ls.Add(so);
                ShowAsg(so.RemoteEndPoint.ToString() + "连接成功");
                Thread rd = new Thread(oneHuDongtwo);
                rd.IsBackground = true;
                Control.CheckForIllegalCrossThreadCalls = false;
                rd.Start();
            }
        }
        private void oneHuDongtwo()
        {
            if (ls.Count == 2)
            {
                rd1 = new Thread(twoHuDongone);
                rd1.IsBackground = true;
                Control.CheckForIllegalCrossThreadCalls = false;
                rd1.Start();
                while (true)
                {
                    byte[] bt =new byte[1024 * 1024 * 2];
                   int r= ls[0].Receive(bt);
                    if (r == 0) 
                    {
                        break;
                    }
                    ls[1].Send(bt);
                }
            }
        }
        Thread rd1;
        private void twoHuDongone()
        {
            while (true)
            {
                byte[] bt = new byte[1024 * 1024 * 2];
                int r = ls[1].Receive(bt);
                if (r == 0)
                {
                    break;
                }
                ls[0].Send(bt);
            }
        }
        List<Socket> ls = new List<Socket>();
        private void ShowAsg(string str)
        {
            userBOX1.AppendText(str + "\r\n");
        }
    }
}
